<?php
namespace app\common\query;
use think\Db;
use app\common\model\BonusAction as BonusActionModel;

class BonusAction
{
	// 错误提示
	private $error='';
	// 消息队列
	private $data=[];
	private $action_name = '';
	// 用户账户
	private $account=[];

	static $status = [
				0 => '未处理',
				1 => '处理成功',
				2 => '处理失败',
				3 => '处理中',
			];

	public function __construct($action_name,$operate_id=null){
		$this->action_name = $action_name;
		$this->model = new BonusActionModel;
		// 消息队列
		if(is_null($operate_id)){
			$this->data = $this->model->where(['action_name'=>$action_name,'status'=>0])->order('create_time','ASC')->select()->toArray();
		}else{
			$this->data = $this->model->where(['action_name'=>$action_name,'operate_id'=>$operate_id,'status'=>0])->order('create_time','ASC')->select()->toArray();
		}
		
	}

	public function getError(){
		return $this->error;
	}

	public function deal(){
		$action_name = $this->action_name;
		$dataList = $this->data;
		if(empty($dataList)){
			return true;
		}
		$memberScoreModel = new \app\common\model\MemberScore;

		if(method_exists($this, $action_name)){
			foreach($dataList as $value):
				$log = $memberScoreModel -> where('id',$value['operate_id'])->value('log');
				$log .= date("Y-m-d H:i:s").'正在处理'.$action_name."奖金;\n";
				$memberScoreModel -> save([
						'log'=>$log,
					],['id'=>$value['operate_id']]);

				$value['action_data'] = unserialize($value['action_data']);
				// 锁消息表
				$update = [
					'status'=>3,
				];
				$this->model->save($update,['id'=>$value['id']]);
				// 处理
				$result = $this->$action_name($value);
				if(false===$result){
					// 失败
					$update = [
						'status' => 2,
						'remark' => $this->error,
					];
					$this->model->save($update,['id'=>$value['id']]);
				}else{
					// 成功
					$update = [
						'status' => 1,
						'remark' => '处理成功',
					];
					$this->model->save($update,['id'=>$value['id']]);
					// 删除消息队列记录
					// 
				}

				$log = $memberScoreModel -> where('id',$value['operate_id'])->value('log');
				$log .= date("Y-m-d H:i:s").'处理'.$action_name.'['.$update['remark']."];\n";
				$memberScoreModel -> save([
						'log'=>$log,
					],['id'=>$value['operate_id']]);
			endforeach;
			return true;
		}else{
			$this->error='方法不存在';
			return false;
		}
	}




	

	private function mathMax($mid,$bonus_name,$bonus,$max,$reason_time){
			
		// 获取当前当日总奖金
		$day = date('Ymd',$reason_time);
		$day_total = model('bonus_member_daily')->where(['mid'=>$mid,'day'=>$day,'bonus_name'=>$bonus_name])->value('total');
		if(!$day_total) $day_total=0;
		// 如果累加奖金大于封顶值，累加奖金等于封顶值，那么净增值等于封顶值减去之前总额；否则净增值等于新增奖金。
		$inc_bonus = ($day_total+$bonus)>$max ? $max-$day_total : $bonus;
		$tip = '';
		if($inc_bonus!=$bonus){
			$tip = '[当日销售补贴超过封顶值]';
		}
		return [
			'inc_bonus' => $inc_bonus,
			'tip' => $tip
		];
			
	}

	private function guanli($mid,$bonus,$reason_time){
		$bonusConfigQuery = new \app\common\query\BonusConfig;
		// 货币配置
		$coinConfig = $bonusConfigQuery::bonusConfig('guanli','coin');
		$coinConfig = unserialize($coinConfig['config_value']);
		// 推荐人配置
		$tuijianConfig = $bonusConfigQuery::bonusConfig('guanli','tuijian');
		$tuijianConfig = unserialize($tuijianConfig['config_value']);
		// 将会员等级作为键名
		$tuijianConfig = array_combine(array_column($tuijianConfig,'level_id'),$tuijianConfig);
		//dump($tuijianConfig);die;
		$floors = [];
		foreach($tuijianConfig as $con):
			$floors[] = sizeof($con['ple_data']);
		endforeach;
		$maxFloor = max($floors); // 配置中的最大邀请层数

		// 找到产生销售补贴的用户$mid范围在$maxFloor以内的所有上级邀请人
		$memberInviterModel = new \app\common\model\MemberInviter;
		$inviters = $memberInviterModel->where(['mid'=>$mid,'index'=>['<',$maxFloor]])->select()->toArray();
		//dump($inviters);die;

		$memberModel = new \app\common\model\Member;
		// 对每个上级邀请人计算管理补贴
		foreach($inviters as $inviter):
			// 获取该邀请人的等级
			$level_id = $memberModel->where(['mid'=>$inviter['inviter_mid']])->value('level_id');
			// 获取该邀请人所在会员等级的配置
			$config = $tuijianConfig[$level_id]['ple_data'];
			
			// 产生销售补贴的用户是该邀请人的第多少层下线
			$floor = $inviter['floor'];
			// 该层是否存在配置中
			if(isset($config[$floor])){
				$bonus_config = $config[$floor]['config'];
				// 基于该配置计算管理补贴
				$guanli_bonus = $bonus*$bonus_config/100;

				// 根据货币分配配置分配货币
				$bonusRecordModel = new \app\common\model\BonusRecord;
				$data =[];
				foreach($coinConfig as $conf):
					// 奖金记录
					$data[] = [
						'bonus_name' => 'guanli',
						'reason_mid' => $mid,
						'effect_mid' => $inviter['inviter_mid'],
						'coin_id' => $conf['coin_id'],
						'amount' => $guanli_bonus*$conf['config']/100,
						'remark' => '用户['.$mid.']获得销售补贴产生管理补贴',
						'reason_time' => $reason_time,
					];
				endforeach;
				$bonusRecordModel -> saveAll($data);
			}else{
				continue;
			}
		endforeach;
	}

	/**
	 * 服务补贴
	 * @return [type] [description]
	 */
	private function fuwu($data){
		$actionData = $data['action_data'];
		$reason_time = $data['create_time'];

		$mid = $actionData['mid'];
		$score = $actionData['score'];
		$agent_mid = $actionData['agent_id'];

		// 获取本奖金配置数据
		$bonusConfigQuery = new \app\common\query\BonusConfig;
		// 货币配置
		$coinConfig = $bonusConfigQuery::bonusConfig(__FUNCTION__,'coin');
		$coinConfig = unserialize($coinConfig['config_value']);
		// 代理中心配置
		$agentConfig = $bonusConfigQuery::bonusConfig(__FUNCTION__,'agent');
		$agentConfig = unserialize($agentConfig['config_value']);
		// 获取该会员所在代理中心的会员等级
		$memberModel = new \app\common\model\Member;
		$agent_level_id = $memberModel->where(['mid'=>$agent_mid])->value('level_id');
		// 根据代理等级获取配置0
		$agentConfig = array_combine(array_column($agentConfig,'level_id'),$agentConfig);
		$config = $agentConfig[$agent_level_id];
		$rate = $config['rate'];

		// 计算奖金
		$bonus = $score*$rate/100;
		// 累计奖金总数
		$bonusMemberTotalModel = new \app\common\model\BonusMemberTotal;
		if($bonusMemberTotalModel->where(['mid'=>$agent_mid,'bonus_name'=>'fuwu'])->find()){
			$bonusMemberTotalModel->where(['mid'=>$agent_mid,'bonus_name'=>'fuwu'])->setInc('total',$bonus);
		}else{
			$bonusMemberTotalModel->insert(['mid'=>$agent_mid,'bonus_name'=>'fuwu','total'=>$bonus]);
		}

		// 货币分配
		$bonusRecordModel = new \app\common\model\BonusRecord;
		$data =[];
		foreach($coinConfig as $conf):
			// 奖金记录
			$data[] = [
				'bonus_name' => 'fuwu',
				'reason_mid' => $mid,
				'effect_mid' => $agent_mid,
				'coin_id' => $conf['coin_id'],
				'amount' => $bonus*$conf['config']/100,
				'remark' => '用户['.$mid.']产生服务补贴',
				'reason_time' => $reason_time,
			];
		endforeach;
		$bonusRecordModel -> saveAll($data);
		return true;
	}

	/**
	 * 业绩累计
	 * @return [type] [description]
	 */
	private function score($data){
		$actionData = $data['action_data'];
		$reason_time = $data['create_time'];
		$score_id = $data['operate_id'];

		$mid = $actionData['mid'];
		$score = $actionData['score'];
		$day = date("Ymd",$reason_time);

		$memberSeterQuery = new \app\common\query\MemberSeter;
        $memberScoreRecordQuery = new \app\common\query\MemberScoreRecord;
        $memberModel = new \app\common\model\Member;
        $memberScoreDailyQuery = new \app\common\query\MemberScoreDaily;

        $seters = $memberSeterQuery->getMemberSeters($mid);
        $seters = array_column($seters,'seter_mid');
        $seters[] = $mid;

        $memberModel->startTrans();
        try{
	        // 增加所有安置人与mid本身业绩
	        foreach($seters as $seter):
	            // 业绩明细记录
	            $remark = '用户['.$mid.']注册或升级产生业绩';
	        	$day = date("Ymd",$reason_time);
	            $data = [
	                'score_id' => $score_id,
	                'reason_mid' => $mid,
	                'effect_mid' => $seter,
	                'score' => $score,
	                'remark'=> $remark,
	                'reason_time' => $reason_time,
	                'reason_day' => $day,
	                'create_time' => time(),
	            ];
	            // 业绩记录 
	            $memberScoreRecordQuery -> saveOneData($data);

	            $update = [
	                'score_total'=>['exp', 'score_total+'.$score],
	            ];
	            // 累计业绩
	            $memberModel->where('mid', $seter)->update($update);

	            // 计算该日新增业绩
	            $dayScore = $memberScoreRecordQuery->dayTotalScore($day,$seter);
	            // 存入新增业绩表
	            $memberScoreDailyQuery->updateDayScore($seter,$day,$dayScore);
	        endforeach;

	        $memberModel->commit();
	    }catch(\Exception $e){
	    	$memberModel->rollback();
	    	$this->error=$e->getMessage();
	    	return false;
	    }
	    return true;

	}

	
}